﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DetetiveKGB.Models;
using System.Web.Routing;

namespace DetetiveKGB.Controllers
{
    [HandleError]
    public class LoginController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new LoginMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string button, LoginModel model, string returnUrl)
        {
            if (button == "Login")
            {
                if (ModelState.IsValid)
                {
                    if (MembershipService.ValidateUser(model.UserName, model.Password))
                    {
                        FormsService.SignIn(model.UserName, false);
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "O nome de usuário e/ou senha estão incorretos.");
                    }
                }
            }
            else
                if (string.IsNullOrEmpty(model.UserName))
                {
                    ModelState.AddModelError("", "O nome de usuário não pode ser vazio.");
                }
                else
                {
                    if (LoginModel.Exists(model.UserName))
                        return RedirectToAction("ForgotPassword", new { username = model.UserName });
                    else
                        ModelState.AddModelError("", "O login informado não existe.");
                }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Logoff()
        {
            FormsService.SignOut();
            return RedirectToAction("Index", "Login");
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Login/Edit/5 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Login/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Login/Delete/5 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Login/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult ForgotPassword(string username)
        {
            LoginModel model = LoginModel.Get(username);
            return View(model);
        }

        [HttpPost]
        public ActionResult ForgotPassword(LoginModel model, string value)
        {
            string password = LoginModel.GetPassword(model.UserName, model.Question, value);
            if (!string.IsNullOrEmpty(password))
            {
                ViewData["password"] = string.Format("A senha é \"{0}\"", password);
            }
            else
            {
                ViewData["Error"] = "A resposta da pergunta está incorreta";
            }
            return View(model);
        }
    }
}
